package apis

import (
	"fmt"
	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"gitee.com/sansaniot/ssiot-core/msg/msgtype"
	"gitee.com/sansaniot/ssiot-core/serrors"
	"github.com/gin-gonic/gin"
	"math/rand"
	"ssadmin/common/utils"
	"ssadmin/internal/admin/models"
	"ssadmin/internal/admin/models/command"
	dto "ssadmin/internal/admin/models/query"
	"ssadmin/internal/admin/service"
	"time"
)

type Register struct {
	api.Api
}

func (e Register) ExistByUsername(c *gin.Context) {
	req := dto.UserGetReq{}
	s := service.User{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors

	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.InvalidParam)
		return
	}

	var userModel models.User
	s.GetByUsername(req.Username, &userModel)

	userPhone := &models.UserPhone{
		UserId:   userModel.UserId,
		UserName: userModel.Username,
		Mobile:   userModel.Mobile,
	}

	if userModel.UserId != "" {
		e.Data(userPhone)
	} else {
		e.Fail(serrors.WrongUser)
	}
}

// Insert 创建用户信息
func (e Register) Insert(c *gin.Context) {
	req := command.RegisterInsertReq{}
	s := service.Register{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	//添加
	err = s.Insert(&req)
	if err != nil {
		e.Logger.Error(err)
		e.Fail(0, err.Error())
		return
	}

	e.Data(req.GetId())
}

// Update 修改用户信息
func (e Register) Update(c *gin.Context) {
	req := command.RegisterUpdateReq{}
	s := service.Register{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}

	err = s.Update(&req)
	if err != nil {
		e.Fail(serrors.Fail)
		return
	}
	e.Data(req.GetId())
}

// SendVerifyCode 发送验证码
func (e Register) SendVerifyCode(c *gin.Context) {
	req := command.VerifyCodeReq{}
	s := service.VerifyCode{}
	ex := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).Errors
	if ex != nil {
		e.Fail(serrors.Fail)
		return
	}
	if !utils.GetCommUtil().CheckMobile(req.Identifier) {
		e.Fail(serrors.WrongPhoneNumber)
		return
	}
	verifyCode := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	// 缓存验证码
	if err := s.CacheCode(&req, verifyCode); err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}
	//发送验证码
	req.MsgCode = msgtype.RegCode.MsgCode
	req.Data = verifyCode
	if err := s.SendCode(&req); err != nil {
		e.Logger.Error(err)
		e.Fail(serrors.Fail)
		return
	}
	e.Ok("操作成功")
}

// 获取手机号
func (e Register) GetPhoneByCode(c *gin.Context) {
	s := service.UserWX{}
	ex := e.MakeContext(c).
		MakeOrm().
		MakeService(&s.Service).Errors
	if ex != nil {
		e.Fail(serrors.Fail)
		return
	}
	code, _ := c.GetQuery("code")
	appId := "wxb8d521a54076b5fe"
	phone := s.GetPhone(code, appId)
	if len(phone) > 0 {
		e.Ok(phone)
	} else {
		e.Fail(serrors.Fail)
	}
}
